<template>
    <!--用户相关操作区开始-->
    <div  class="card">
        <el-button type="primary" @click="handleAdd">新增用户</el-button>
        <el-button type="danger" @click="deleteUserBatch">批量删除</el-button>
<!--        <el-button type="success">批量导入</el-button>-->
<!--        <el-button type="warning">批量导出</el-button>-->
        <el-input :prefix-icon="Search" placeholder="请输入角色名"
                  v-model="data.name"
                  clearable
                  style="width: 190px; margin: 0 10px"/>
        <el-select
            v-model="rolename"
            clearable
            placeholder="请选择角色"
            style="width: 190px; margin-right: 10px">  <!-- clearable属性可将选择器清空，仅适用于单选 -->
            <el-option
                v-for="item in options"
                :key="item.rolename"
                :label="item.label"
                :value="item.rolename"/>
        </el-select>
        <el-button @click="reset">重置</el-button>
        <el-button type="primary" @click="load">查询</el-button>
    </div>
    <!--用户相关操作区结束-->

    <!--用户信息展示区开始-->
    <div class="card">
        <!-- el-table-column 的 template 标签中使用 #default="scope"，这是作用域插槽的写法，通过 scope 可以访问到当前行的数据对象 scope.row。 -->
        <el-table :data="data.tableData" style="width: 100%; min-height: 350px"
                  :header-cell-style="{ fontWeight: 'bold', color: '#1d1c1c', textAlign: 'center', backgroundColor: '#f5f4f1'}"
                  :cell-style="{ textAlign: 'center' }"
                  @selection-change="handleSelectionChange"
        >  <!-- :header-cell-style ： 表头设置样式、  :cell-style ： 表格内容设置样式 -->
            <el-table-column type="selection" width="45" />  <!--选择框-->
            <el-table-column prop="profile_photo_path" label="头像" width="80">
                <template #default="scope">
                    <!--&lt;!&ndash; :fit="cover" : 当展示类型为图片的时候，设置图片如何适应容器 / shape="circle" : 图片展示样式 circle圆形-->
                    <el-avatar :src="scope.row.profile_photo_path" :size="40" fit="cover" shape="circle" @error="errorHandler">
                        <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" alt="加载错误"/> <!--图片加载失败的回退行为-->
                    </el-avatar>
                </template>
            </el-table-column>
            <el-table-column prop="username" label="用户名" width="100" show-overflow-tooltip/>
            <el-table-column prop="created_at" label="创建时间" show-overflow-tooltip/>
            <el-table-column property="email" label="电子邮件" width="200" show-overflow-tooltip/>  <!--当内容太长时，它会分成多行。您可以使用 show-overflow-tooltip 将其保留在一行中-->
            <el-table-column prop="phone" label="联系电话" width="120" show-overflow-tooltip/>
            <el-table-column prop="role.roleName" label="角色" />
            <el-table-column fixed="right" label="操作" min-width="80">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
                    <el-button link type="danger" size="small" @click="deleteUser(scope.row.user_id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <!--用户信息展示区结束-->

    <!--数据分页功能区开始-->
    <div class="card">
        <el-pagination
            v-model:current-page="data.pageNum"
            v-model:page-size="data.pageSize"
            :page-sizes="[5, 10, 20]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total"
            @current-change="load"
            @size-change="load"
        />  <!--@current-change : 改变时触发，再次请求一次数据，实现分页查询;  @size-change: 数量改变触发-->
    </div>
    <!--数据分页功能区结束-->


    <!-- 新增/修改用户弹窗开始 -->
    <el-dialog title="新增用户" v-model="data.dialogFormVisible" width="400" destroy-on-close align-center>
        <el-form ref="formRef" :model="data.userForm" :rules="data.rules" label-width="80px" style="padding: 20px 30px 10px 20px">
            <el-form-item label="用户名称" prop="username">
                <el-input v-model="data.userForm.username" autocomplete="off" style="width: 230px"/>
            </el-form-item>
            <el-form-item prop="phone" label="手机电话">
                <el-input v-model="data.userForm.phone" autocomplete="off" style="width: 230px"/>
            </el-form-item>
            <el-form-item prop="email" label="电子邮箱">
                <el-input v-model="data.userForm.email" autocomplete="off" style="width: 230px"/>
            </el-form-item>
            <el-form-item label="用户角色" prop="role_name">
                <el-select  v-model="data.userForm.role_name" clearable placeholder="请选择角色" style="width: 230px">  <!-- clearable属性可将选择器清空，仅适用于单选 -->
                    <el-option v-for="item in role_options" :key="item.role_name" :label="item.role_label" :value="item.role_name"/>
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="data.dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="sava">保存</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 新增用户弹窗开始 -->
</template>

<script setup>
import {ref, reactive, toRefs} from "vue";
import { markRaw } from 'vue'
import {Delete, Search} from '@element-plus/icons-vue'
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";

const formRef = ref();

// Select 选择器
let rolename = ref('')
const options = [
    {
        rolename: 'USER',
        label: 'USER',
    },
    {
        rolename: 'ADMIN',
        label: 'ADMIN',
    },
]

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
// 数据绑定
const data = reactive({
    name: null,
    pageNum: 1, //当前页面
    pageSize: 5, //页面数量
    total: 0,  //数据总数
    tableData: [], //用户列表数据
    dialogFormVisible: false, //新增/修改弹窗默认关闭
    userForm: {}, //用户信息表单
    rows: [], // 多选用户数据
    rules: {
        username: [
            { required: true, message: "请填写用户名", trigger: 'blur' },
            {max:15, message: "账号最多15位", trigger: 'blur'}
        ],
        email: [
            { required: true, message: "请填写邮件地址", trigger: 'blur' },
            {pattern: emailRegex, message: '邮件格式不符', trigger: "blur"},
            { max: 40, message: '最多输入40位', trigger: 'blur' },
        ],
        role_name: [
            { required: true, message: "请选择对应角色", trigger: 'change' }, // trigger:何时触发验证
        ],
    },
})

//分页 + 条件 查询
const load = () => {
    // 前后端数据查询
    request.get('/api/admin/selectPage', {
        params : {
            pageNum : data.pageNum,
            pageSize : data.pageSize,  //添加参数给后端实现分页
            name: data.name,
            rolename: rolename.value,
        }
    }).then(res => {
        if (res.code === "200") {
            data.tableData = res.data.list // 获取后端返回的所有用户信息
            data.total = res.data.total    // 后台数据总数
        } else {
            ElMessage.error(res.msg)
        }
    })
}
load();

//重置按钮
const reset = () => {
    data.name = null
    rolename.value = null
    load()
}


// avatar头像
const state = reactive({
    url: data.tableData.profile_photo_path,
})
const { url } = toRefs(state)
const errorHandler = () => true //图片加载失败的回退行为





// 兼容 新增和修改
const sava = () => {
    data.userForm.user_id ? editUser() : add()
}

// 新增用户的角色选择
let role_name = ref('')
const role_options = [
    { role_name: 'USER', role_label: 'USER' },
    { role_name: 'ADMIN', role_label: 'ADMIN' },
]
//弹窗点击事件
const handleAdd = () => {
    data.dialogFormVisible = true
    data.userForm = {}
    role_name.value = null
}
//新增用户方法
const add = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            console.log(valid);
            request.post('/api/admin/add', data.userForm, {
                params: { role_name: data.userForm.role_name }
            }).then(res => {
                if (res.code === '200') {
                    ElMessage.success('新增用户成功')
                    load() //加载最新数据
                    data.dialogFormVisible = false // 关闭弹窗
                } else {
                    ElMessage.error(res.msg)
                }
            })
        }
    })
}


// 用户修改点击事件方法
const handleEdit = row => {
    data.userForm = JSON.parse(JSON.stringify(row)) // 深度拷贝数据：将数据转化为字符串再将字符串转化为json对象 使得与form为两个独立的数据
    data.dialogFormVisible = true
    data.userForm.role_name = row.role.roleName // 反选
}
// 用户弹窗修改点击事件方法
const editUser = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            request.put('/api/admin/update', data.userForm, {
                params: { role_name: data.userForm.role_name }
            }).then(res => {
                if (res.code === '200') {
                    ElMessage.success('修改用户成功')
                    load() //加载最新数据
                    data.dialogFormVisible = false // 关闭弹窗
                } else {
                    ElMessage.error(res.msg)
                }
            })
        }
    })
}


//删除单个用户点击事件
const deleteUser = (user_id) => {
    ElMessageBox.confirm('您确定删除此用户嘛 此操作不可逆转！请谨慎操作！', '删除确认', {type: 'warning', icon: markRaw(Delete),}).then(res => {
        request.delete('/api/admin/delete/' + user_id).then(res => {
            if (res.code === '200') {
                ElMessage.success("用户删除成功")
                load()//加载最新数据
            } else {
                ElMessage.error(res.msg)
            }
        })
    }).catch(err => {})
}

// table 的多选事件 @selection-change="handleSelectionChange"
const handleSelectionChange = (rows) => {  // rows 就是实际选择的数组
    data.rows = rows
}
// 批量删除用户事件方法
const deleteUserBatch = () => {
    if (data.rows.length === 0) {
        ElMessage.warning('请选择数据')
        return
    }
    ElMessageBox.confirm('删除后无法恢复，您确认删除吗？', '删除确认', { type: 'warning', icon: markRaw(Delete)}).then(res => {
        request.delete('/api/admin/deleteUserBatch', { data: data.rows }).then(res => {
            if (res.code === '200') {
                ElMessage.success('批量删除成功')
                load()
            } else {
                ElMessage.error(res.msg)
            }
        })
    }).catch(err => {})
}
</script>

<style scoped>

</style>